// allocate buffer use ascii code
// support ascii utf8 utf16le(ucs2) base64 latin1 binary hex
const buf = Buffer.from('hello', 'ascii');

// output hex string
console.log(buf.toString('hex'));

// output base64 string
console.log(buf.toString('base64'));

// create length 10 and fill with 0 buffer
const buf1 = Buffer.alloc(10);

// create len 10 with fill 0x1 buffer
const buf2 = Buffer.alloc(10, 1);

// create len 10 uninit buffer, fast than alloc(), but may be dirty, need use fill() write() 
const buf3 = Buffer.allocUnsafe(10);
// write 4 byte data
buf3.write('hi');
// read from buf
console.log(buf3.toString());


//create buf with value array
const buf4 = Buffer.from([1,2,3]);

// create buf with string
const buf5 = Buffer.from('text');

// create buf with string and code latin1
const buf6 = Buffer.from('test', 'latin1');


const buf7 = Buffer.alloc(26);
for (var i=0; i<26; i++) {
	buf7[i] = i + 97;
}
// output a-z
console.log(buf7.toString('ascii'));
// output a-e
console.log(buf7.toString('ascii', 0, 5));
// output a-e use utf8
console.log(buf7.toString('utf8', 0, 5));

// to Json
console.log(buf7.toJSON());

const buf8 = Buffer.from([0x1,0x2,0x3]);
const json = JSON.stringify(buf);

console.log(json);

const copy = JSON.parse(json, (key,value) => {
	console.log('key ->', key, 'value ->', value);
	return value && value.type === 'Buffer' ? Buffer.from(value.data) : value;
});

console.log(copy);

// merge
console.log(Buffer.concat([buf5, buf6]));


console.log(buf5.compare(buf6));

// insert to buf6 pos 1
buf6.copy(buf5, 1);
console.log(buf6.toString(), buf6.length);

// cut 0-2
console.log(buf6.slice(0,2));





